import re
from bs4 import BeautifulSoup
import os
import aiohttp
import aiofiles
import asyncio
import requests
from  tld import get_fld


headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36"
}
domain = " https://video.dious.cc"


# 获取页面的m3u8文件
def get_index_m3u8(url):
    index_resp = requests.get(url,headers= headers)
    index_soup = BeautifulSoup(index_resp.text,"html.parser")
    href = index_soup.find("a",id="1").get("href")
    print("拿到第一个m3u8为: ",href)
    return href


def get_m3u8_info(index_m3u8):
    info_resp = requests.get(index_m3u8,headers = headers)
    with open("down/jg.m3u8",mode="w")as info_fo:
        info_fo.write(info_resp.text)



def get_real_address_m3u8_url():
    with open("down/jg.m3u8",mode="r",encoding="utf-8") as get_real_fo:
        for address in get_real_fo:
            if address.startswith("#"):
                continue
            real_url = domain + address.strip()
    real_resp = requests.get(real_url,headers =headers)
    with open("down/real.m3u8",mode="wb") as real_fo:
        real_fo.write(real_resp.content)
        print("下载成功")


def download_ts():
    count = 0;
    with open("down/real.m3u8", mode="r", encoding="utf-8") as f:
        for line in f:
            line.strip()
            if line.startswith("#"):
                continue
            print(line)
            line.strip()
            resp_line = requests.get(line,headers=headers)
            with open(f"video/ts{count}.ts",mode="wb")as fl:
                fl.write(resp_line.content)
            count += 1




async def download_ts(line,session):
        async with session.get(line,headers=headers) as resp:
            async with aiofiles.open("down/ts/"+str(line).split("/")[-1] ,mode="wb") as f:
                await f.write(await resp.content.read())
        print("下载成功：",line)



# 异步多任务下载
async def aio_down():
    tasks = []

    async with aiohttp.ClientSession() as session:
        async with aiofiles.open("down/real.m3u8",mode = "r") as fo:
            async for line in fo:
                if line.startswith("#"):
                    continue
                line.strip()
                print("b")
                tasks.append(download_ts(line,session))
                print(tasks)

            await asyncio.wait(tasks)#等待任务结束
            print("结束")


if __name__ == '__main__':
    # index_url = "http://www.kanjule.cn/qxplay/110.html"
    # index_m3u8_url = get_index_m3u8(index_url)
    # get_m3u8_info(index_m3u8_url)
    # get_real_address_m3u8_url()
    # 启动任务
    # download_ts()
    asyncio.get_event_loop().run_until_complete(aio_down())

